package com.japher.hackson.activity;

import java.util.Hashtable;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import baidumapsdk.demo.OverlayDemo;

import com.baidu.common.async_http.IResponseListener;
import com.baidu.common.json.JsonSerializer;
import com.baidu.common.views.LoadingDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfigeration;
import com.baidu.mapapi.map.MyLocationConfigeration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.japher.hackson.HacksonApplication;
import com.japher.hackson.R;
import com.japher.hackson.document.CommentItem;
import com.japher.hackson.document.CommentItem.Loc;
import com.japher.hackson.requests.LoadCommentRequest;
import com.japher.hackson.response.BaseResponse;
import com.japher.hackson.response.CommentResponse;
import com.japher.hackson.utils.Tools;

public class MainActivity extends Activity implements OnClickListener{

    
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LoadingDialog mLoadingView;
    private ImageView mBtnNaviBack;
    private Marker mMarkerA;
    private InfoWindow mInfoWindow;
    BitmapDescriptor bdA = BitmapDescriptorFactory.fromResource(R.drawable.da_marker_red);
    private Hashtable<Marker, CommentItem> mDataCache = new Hashtable<Marker, CommentItem>();
    private Button mBtnAdd;
    
    private String[] tmpLatitude = {
        
        "116.313441","116.314802","116.316401","116.313603","116.31129"
    };
    private String[] tmpLongtitue = {
        
        "40.047868","40.048448","40.048158","40.04694","40.048089"
    };
    
    private CommentItem currentItem;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.layout_main);
        mBtnNaviBack = (ImageView) findViewById(R.id.icon_right);
        mBtnNaviBack.setBackgroundResource(R.drawable.rigel_navi_menu_btn_selector);
        mBtnNaviBack.setOnClickListener(this);
        mBtnNaviBack.setVisibility(View.GONE);
        
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.5f);
        mBaiduMap.setMapStatus(msu);
        mBaiduMap.setMyLocationEnabled(true);
        mBtnAdd = (Button)findViewById(R.id.btn_add);
        mBtnAdd.setOnClickListener(this);
        
        mLoadingView = new LoadingDialog(this, false, null);
        mLoadingView.setMessage("正在加载数据...");
        
        mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
            public boolean onMarkerClick(final Marker marker) {
                
                
                Button button = new Button(getApplicationContext());
                button.setBackgroundResource(R.drawable.bg_map_for_cinema);
                int padding = Tools.getPixelByDip(MainActivity.this, 15);
                button.setPadding(padding, padding/2, (int)(padding*1.5), padding);
                
                button.setTextColor(Color.WHITE);
                OnInfoWindowClickListener listener = null;
                if(mDataCache.containsKey(marker)){
                    
                    final CommentItem item = mDataCache.get(marker);
                    button.setText(item.getTitle());
                    currentItem = item;
                    
                    listener = new OnInfoWindowClickListener() {
                        
                        @Override
                        public void onInfoWindowClick() {
                            Intent intent = new Intent();
                            
                            String json = JsonSerializer.getInstance().serialize(item);
                            intent.setClass( MainActivity.this, DetailActivity.class);
                            intent.putExtra("data", json);
                            MainActivity.this.startActivity(intent);
                        }
                    };
                }
                
                final LatLng ll = marker.getPosition();
                Point p = mBaiduMap.getProjection().toScreenLocation(ll);
                
                Drawable d = getResources().getDrawable(R.drawable.da_marker_red);
                p.y -= d.getIntrinsicHeight();
                LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
                
                mInfoWindow = new InfoWindow(button, llInfo, listener);
                mBaiduMap.showInfoWindow(mInfoWindow);
                return true;
            }
        });
       
        
        locate();
    }
    private Handler handler = new Handler();
    
    private void loadRemoteData(String longt,String lati,float dis){
        mLoadingView.show();
        LoadCommentRequest request = new LoadCommentRequest(longt, lati, dis);
        request.StartRequest(new IResponseListener() {
            
            @Override
            public void onRequestComplete(BaseResponse response) {
                mLoadingView.dismiss();
                mDataCache.clear();
                
                if(response != null && response.isSuccess() && response instanceof CommentResponse){
                    
                    CommentResponse res = (CommentResponse)response;
                    setup(res.getData());
                }else{
                    
                    CommentItem[] items = new  CommentItem[5];
                    for(int i = 0 ; i < items.length ; i++){
                        CommentItem item = new CommentItem();
                        item.set_id(System.currentTimeMillis()+"");
                        item.setBody("吃到一半的时候就觉得特别腻，根本没有吃北京小吃的清爽感。");
                        item.setTitle("这里的东西很好吃！^——^");
                        item.setCreatedAt("2014-06-26 18:47:00");
                        item.setLoc(new Loc(tmpLatitude[i],tmpLongtitue[i]));
                        items[i] = item;
                    }
                    setup(items);
                    //Toast.makeText(MainActivity.this, "访问失败", 3000).show();
                }
            }
            
        });
    }
    
    
    
    private void setup(CommentItem[] data){
        if(data ==null || data.length == 0){
            return;
        }
        
        for(int i = 0 ; i < data.length ;i++)
        {
            CommentItem item = data[i];
            if(item == null){
                continue;
            }
            
            final Loc loc = item.getLoc();
            if(loc == null){
                continue;
            }
            
            try{
                
                double l1 = Double.parseDouble(loc.getLat());
                double l2 = Double.parseDouble(loc.getLng());
                LatLng llA = new LatLng(l1, l2);
                OverlayOptions ooA = new MarkerOptions().position(llA).icon(bdA).zIndex(9);
                mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));
                
                mDataCache.put(mMarkerA, item);
                
            }catch(Exception e){
                continue;
            }
            
        }
    }
    
    private void locate(){
        final HacksonApplication application = (HacksonApplication)getApplication();
        application.locate(new BDLocationListener() {
            
            @Override
            public void onReceivePoi(BDLocation arg0) {
                
            }
            
            @Override
            public void onReceiveLocation(final BDLocation arg0) {
                try
                {
                    if (application.mLocationClient != null)
                    {
                        application.mLocationClient.stop();
                        application.mLocationClient.unRegisterLocationListener(this);
                    }
                    
                    if (Tools.isBaiduGeoSuccess(arg0))
                    {
                        arg0.setLatitude(40.056915);
                        arg0.setLongitude(116.308075);
                        setupMyLocation(arg0);
                        
                        handler.postDelayed(new Runnable() {
                            
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                loadRemoteData(arg0.getLongitude()+"",arg0.getLatitude()+"",1000.0f);
                            }
                        }, 2000);
                    }
                }
                catch (Exception e)
                {

                }
            }
        });
    }
    
    private void setupMyLocation(BDLocation location)
    {
        mBaiduMap.setMyLocationEnabled(true);  
        MyLocationData locData = new MyLocationData.Builder()  
            .accuracy(location.getRadius())  
            // 此处设置开发者获取到的方向信息，顺时针0-360  
            .direction(0).latitude(location.getLatitude())  
            .longitude(location.getLongitude()).build();  
        // 设置定位数据  
        mBaiduMap.setMyLocationData(locData);  
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）  
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);  
        
        MyLocationConfigeration config = new MyLocationConfigeration(LocationMode.COMPASS, true, mCurrentMarker);  
        
        mBaiduMap.setMyLocationConfigeration(config);
        // 当不需要定位图层时关闭定位图层  
       //mBaiduMap.setMyLocationEnabled(false);
        
        
    }
    
    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
        mMapView.onDestroy();
        super.onDestroy();
        // 回收 bitmap 资源
    }

    @Override
    public void onClick(View v) {
        if(v == mBtnAdd){
            Intent intent = new Intent(this,EditActivity.class);
            startActivity(intent);
            
        }else{
            Intent intent = new Intent(this,OverlayDemo.class);
            this.startActivity(intent);
        }
    }
}
